<template>
  <div class="text-preview">
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading" :size="50">
        <Loading />
      </el-icon>
      <p>文本加载中...</p>
    </div>

    <div v-else-if="error" class="error-container">
      <el-icon :size="80">
        <WarningFilled />
      </el-icon>
      <p>{{ error }}</p>
    </div>

    <el-scrollbar v-else class="text-container">
      <div class="text-header">
        <el-tag type="info" size="small">{{ fileExtension.toUpperCase() }}</el-tag>
        <span class="file-size">{{ formatFileSize(file.size) }}</span>
        <span class="line-count">共 {{ lineCount }} 行</span>
      </div>
      <pre class="text-content"><code>{{ textContent }}</code></pre>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { Loading, WarningFilled } from '@element-plus/icons-vue'
import { readFileContent } from '../../utils/fileHelper'

const props = defineProps({
  file: {
    type: Object,
    required: true
  }
})

const loading = ref(false)
const error = ref('')
const textContent = ref('')

// 获取文件扩展名
const fileExtension = computed(() => {
  const parts = props.file.name.split('.')
  return parts.length > 1 ? parts[parts.length - 1] : 'txt'
})

// 计算行数
const lineCount = computed(() => {
  if (!textContent.value) return 0
  return textContent.value.split('\n').length
})

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

// 加载文本文件
const loadText = async () => {
  try {
    loading.value = true
    error.value = ''
    textContent.value = ''

    let content = ''
    
    // 如果是 URL 文件，使用 fetch
    if (props.file.isUrl) {
      console.log('✓ 使用 URL 加载文本:', props.file.url)
      const response = await fetch(props.file.url)
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
      content = await response.text()
    } else {
      // 本地文件，使用 FileReader
      console.log('✓ 使用本地文件加载文本')
      content = await readFileContent(props.file.raw, 'text')
    }
    
    textContent.value = content
    loading.value = false
  } catch (err) {
    console.error('文本加载失败:', err)
    if (err.message.includes('CORS') || err.message.includes('Failed to fetch')) {
      error.value = '文本加载失败：CORS 跨域限制。建议：1) 下载后上传 2) 使用代理 URL'
    } else {
      error.value = '文本文件加载失败：' + err.message
    }
    loading.value = false
  }
}

watch(() => props.file, () => {
  if (props.file) {
    loadText()
  }
}, { immediate: true })
</script>

<style scoped>
.text-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #409EFF;
}

.error-container {
  color: #F56C6C;
}

.loading-container p,
.error-container p {
  margin-top: 16px;
  font-size: 14px;
}

.text-container {
  flex: 1;
  overflow: auto;
}

.text-header {
  position: sticky;
  top: 0;
  z-index: 10;
  padding: 12px 40px;
  background: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 13px;
  color: #606266;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.file-size,
.line-count {
  color: #909399;
}

.text-content {
  padding: 30px 40px;
  background: #ffffff;
  margin: 0;
  min-height: calc(100vh - 200px);
  font-family: 'Consolas', 'Monaco', 'Courier New', 'Menlo', monospace;
  font-size: 14px;
  line-height: 1.8;
  color: #2c3e50;
  white-space: pre;
  word-wrap: normal;
  overflow-x: auto;
  tab-size: 4;
  -moz-tab-size: 4;
}

.text-content code {
  font-family: inherit;
  font-size: inherit;
  color: inherit;
  background: none;
  padding: 0;
}

/* 代码着色（基础） */
.text-content {
  counter-reset: line;
}
</style>

